-module(tcp_IO).
-export([connection/2]).

connection(Master, Port)->
	io:format("Starting connection server on ~p...~n",[Port]),
	case gen_tcp:listen(Port, [binary, {packet,0}, 
									{reuseaddr, true}, 
									{active, true}]) of		 	
		{ok, Listen}->
			Master ! {self(), ok},
			connectLoop(self(), Listen);
		Error -> 
			Master ! {self(), Error}
	    end. 
	
connectLoop(Connection, Listen)->
	io:format("start accepting~n"),
	Self = self(), 
	spawn_link(fun()->seq_loop(Listen, Self) end),
	
	receive
		{Child, ok} ->
			connectLoop(Connection, Listen);
		{Child, error}->
			exit(terminate)
	end.
	
seq_loop(Listen, Controller)->
	case  gen_tcp:accept(Listen) of 
		{ok, Socket} -> 
			io:format("accept occured~n"),
			Controller ! {self(), ok},
			loop(Socket,Listen, Controller)
	end.
	
loop(Socket, Listen, Controller)->
			receive
				{tcp, Socket, Bin}->		
					Str = binary_to_list(Bin),
					io:format("Request: ~p~n", [Str]),
					gen_tcp:send(Socket, httpResp:buildHeader("<html><body><h1>schummer</h1></body></html>")),
					gen_tcp:close(Socket);
				{tcp_closed, Socket}->
					io:format("server closed~n"),
					io:format(Socket, "close message>"),
 					Controller ! {close};
				Any->  io:format("BUMMER~n")
			end.
	